package com.lazyframework.commons.util;

/**
 * 随机数(字符串)工具类
 * @author maoning in 2019.11.18
 */
public class RandomUtils {

    // Fields

    private static final char[] CHARACTER_DICTIONARY = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
            'k', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v',
            'w', 'x', 'y', 'z'
    };

    // Constructors

    private RandomUtils() {
    }

    // Static Methods

    /**
     * 返回指定范围的随机数
     *
     * @param from
     * @param to
     * @return [from, to)
     */
    public static int randomNum(int from, int to) {
        return (int) (Math.random() * (from - to) + to);
    }

    /**
     * 以字符串类型返回指定范围的随机书
     *
     * @param from
     * @param to
     * @return [from, to)
     */
    public static String randomNumAsString(int from, int to) {
        return String.valueOf(randomNum(from, to));
    }

    /**
     * 返回四位不含字母的随机验证码
     *
     * @return
     */
    public static String randomVCode() {
        return randomVCode(4);
    }

    /**
     * 返回指定长度不含字母的随机验证码
     *
     * @param length
     * @return
     */
    public static String randomVCode(int length) {
        return randomVCode(length, false);
    }

    /**
     * 返回指定长度包含字母的随机验证码
     *
     * @param length
     * @param containsLetter
     * @return
     */
    public static String randomVCode(int length, boolean containsLetter) {
        StringBuilder code = new StringBuilder();
        do {
            if (containsLetter) {
                code.append(CHARACTER_DICTIONARY[randomNum(0, 34)]);
            } else {
                code.append(CHARACTER_DICTIONARY[randomNum(0, 10)]);
            }
        } while (code.length() != length);
        return code.toString();
    }

}
